/* 
 * Copyright TLR Team, Inc. All Rights Reserved.
 */



/* global AMap */

TLR.controllers
.controller("DashBoardHealthMapViewCtrl", function ($rootScope, $scope, $routeParams, MAP, HEALTH, EBanDeviceSrv, EBanDeviceMockSrv) {
    $rootScope.view = $routeParams.view;
    $scope.alertMessageList = [];
    $scope.init = function () {
        $scope.validHealthDevices = [];
        $scope.invalidHealthDevices = [];
        $scope.showRelationList = {};
        $scope.validHealthDeviceCount = 0;
        $scope.invalidHealthDeviceCount = 0;
    };
    $scope.init();
    var w = $("#health-map-container-parent").width();
    var h = $(window).height();
    var min_height = MAP.map_min_height + MAP.map_info_panel;
    h = h < min_height ? min_height : h;
    var map_container_id_name = "health-map-container";
    var map_container_id = "#" + map_container_id_name;
    $(map_container_id).width(w);
    $(map_container_id).height(h - 400);
    $scope.healthListTimer = setInterval(function () {
        $scope.$broadcast(HEALTH.event.list);
        // 1 min
    }, 60 * 1000);
    $scope.$on('$destroy', function () {
        // clear timer
        clearInterval($scope.healthListTimer);
    });

    $scope.webSocketInit = function () {
        try {
            $scope.scopeDestroyed = false;
            $scope.webSocket = new WebSocket($scope.webSocketAddress);
            $scope.webSocket.onmessage = $scope.onWebSocketMessage;
            $scope.webSocket.onclose = $scope.onWebSocketClose;
            $scope.webSocket.onerror = $scope.onWebSocketError;
        } catch (err) {
            alert("健康仪服务异常");
        }
        $scope.$on('$destroy', function () {
            $scope.scopeDestroyed = true;
            $scope.webSocket.close();
        });
    };
    $scope.onWebSocketError = function (evt) {
        $scope.onWebSocketClose();
        console.log(evt);
    };
    $scope.onWebSocketClose = function () {
        if (!$scope.scopeDestroyed) {
            setTimeout($scope.webSocketInit, 10000);
            console.log("closing and reconnecting");
        }
    };
    $scope.onWebSocketMessage = function (event) {
        console.log("Websocket:", event);
        try {
            var alertMessage = JSON.parse(event.data);
            $scope.$apply(function () {
                $scope.alertMessageList.push(alertMessage);
                $("#alertWAV")[0].play();
            });
            console.log(alertMessage);
        } catch (err) {
            alert("服务器推送消息无效");
            console.log(JSON.stringify(err));
        }
    };
    EBanDeviceSrv.service_address(function (resp) {
        if (resp.code !== 0) {
            alert("不能获取健康仪服务信息");
            return;
        }
        try {
            $scope.webSocketAddress = resp.data;
            $scope.webSocketInit();
        } catch (err) {
            $scope.onWebSocketClose();
        }
        $scope.$on('$destroy', function () {
            $scope.webSocket.close();
        });
    });
    $scope.$on("WindowResize", function () {
        var w = $("#health-map-container-parent").width();
        var h = $(window).height();
        $(map_container_id).width(w);
        $(map_container_id).height(h - 310);
    });
    $scope.onViewDetail = function (action) {
        $("#alertWAV")[0].pause();
        $scope.health_action = action;
        if (action === 'normal') {
            $scope.devices = $scope.validHealthDevices;
        } else if (action === "fault") {
            $scope.devices = $scope.invalidHealthDevices;
        } else if (action === "alert") {

        }
    };
    $scope.onShowRelations = function (code, index) {
        $scope.showRelationList[index] = !$scope.showRelationList[index];
        $scope.alertRelations = null;
        if ($scope.showRelationList) {
            EBanDeviceSrv.alert_relations({code: code}, function (res) {
                if (res.code === 0) {
                    $scope.alertRelations = res.data;
                } else {
                    alert(res.message);
                }
            });
        }
    };
    $scope.saveDescription = function (id, alertDescription) {
        EBanDeviceSrv.save_desc({
            id: id,
            description: alertDescription
        }, function (res) {
            if (res.code === 0)
                alert("保存成功");
            else
                alert(res.message);
        });
    };
    $scope.closeCase = function (id, description) {
        if (!description || description === "") {
            alert("必须填写处理结果");
            return;
        } else {
            EBanDeviceSrv.save_desc({
                id: id,
                description: description
            }, function (res) {
                if (res.code === 0) {
                    EBanDeviceSrv.close_case({id: id}, function (res) {
                        if (res.code === 0) {
                            alert("处理成功");
                            $scope.$broadcast(HEALTH.event.alert_list);
                        } else
                            alert(res.message);
                    });
                } else {
                    alert(res.message);
                }
            });
        }
    };
    var map = new AMap.Map(map_container_id_name, {
        resizeEnable: true,
        zoom: 10,
        center: [121.496548, 31.239432],
        animateEnable: false
    });
    map.plugin(["AMap.ToolBar"], function () {
        map.addControl(new AMap.ToolBar());
    });

    $scope.$on(HEALTH.event.alert_list, function () {
        EBanDeviceSrv.alert_list(function (res) {
            if (res.code === 0) {
                $scope.alertMessageList = res.data;
            } else {
                alert(res.message);
            }
        });
    });

    $scope.$on(HEALTH.event.list, function () {
        EBanDeviceSrv.fast_map_info(function (healthResp) {
            if (healthResp.code !== 0) {
                alert(healthResp.message);
                return;
            }
            $scope.init();
            $scope.healthDevices = healthResp.data;
            if ($scope.healthDevicesMock && $scope.healthDevicesMock.length > 0) {
                $scope.healthDevices = $scope.healthDevices.concat($scope.healthDevicesMock);
            }
            map.clearMap();  // 清除地图覆盖物
            for (var i = 0; i < $scope.healthDevices.length; ++i) {
                var healthDevice = $scope.healthDevices[i];
                if (healthDevice.status === 0 || healthDevice.enabled === false) {
                    $scope.invalidHealthDevices.push(healthDevice);
                    continue;
                } else {
                    $scope.validHealthDevices.push(healthDevice);
                }
                var div = document.createElement('div');
                $(div).css("border-radius", "8px")
                .css("background-color", $scope.getHealthColor(healthDevice.point))
                .css("width", "65px")
                .css("height", "32px")
                .css("color", "#fff")
                .css("font-size", "24px")
                .css("text-align", "center");
                div.innerHTML = healthDevice.point;
                var marker = new AMap.Marker({
                    map: map,
                    position: [healthDevice.lng, healthDevice.lat],
                    offset: new AMap.Pixel(-30, -10),
                    content: div
                });
                marker.infoWindow = new AMap.InfoWindow({
                    isCustom: true, //使用自定义窗体
                    content: "<div class='health-info-window'><div class='health-info'>"
                    + "姓名:" + healthDevice.nick_name + "<br>"
                    + "手机:" + healthDevice.mobile + "<br>"
                    + "地址:" + healthDevice.position + "<br>"
                    + "</div></div>",
                    offset: new AMap.Pixel(6, -25)
                });
                AMap.event.addListener(marker, 'click', function (evt) {
                    console.log(evt.target);
                    if (evt.target.infoWindow.getIsOpen())
                        evt.target.infoWindow.close();
                    else
                        evt.target.infoWindow.open(map, evt.target.getPosition());
                });
            }
            $scope.invalidHealthDeviceCount = $scope.invalidHealthDevices.length;
            $scope.validHealthDeviceCount = $scope.validHealthDevices.length;
            map.setFitView();
        });
    });
    // TODO Temp used
    /*
     EBanDeviceMockSrv.list(function (resp) {
     $scope.healthDevicesMock = resp.data;
     $scope.$broadcast(HEALTH.event.list);
     }) //*/
    // TODO
    $scope.$broadcast(HEALTH.event.alert_list);
    $scope.$broadcast(HEALTH.event.list);
})
.controller("DashBoardCarMapViewCtrl", function ($rootScope, $scope, $routeParams, MAP, CAR, VehicleSrv) {
    $rootScope.view = $routeParams.view;
    $scope.carList = null;
    $scope.init = function () {
        $scope.readyServiceDevices = [];
        $scope.inServiceDevices = [];
        $scope.stopServiceDevices = [];
        $scope.invalidServiceDevices = [];
    };
    $scope.init();
    var w = $("#car-map-container-parent").width();
    var h = $(window).height();
    var min_height = MAP.map_min_height + MAP.map_info_panel;
    h = h < min_height ? min_height : h;
    var map_container_id_name = "car-map-container";
    var map_container_id = "#" + map_container_id_name;
    $(map_container_id).width(w);
    $(map_container_id).height(h - 400);
    $scope.carListTimer = setInterval(function () {
        $scope.$broadcast(CAR.event.list);
    }, 1000 * 30);
    $scope.$on('$destroy', function () {
        // clear timer
        clearInterval($scope.carListTimer);
    });
    $scope.$on("WindowResize", function () {
        var w = $("#car-map-container-parent").width();
        var h = $(window).height();
        $(map_container_id).width(w);
        $(map_container_id).height(h - 310);
    });
    $scope.onViewDetail = function (action) {
        $scope.health_action = action;
        if (action === 'ready') {
            $scope.devices = $scope.readyServiceDevices;
        } else if (action === "stop") {
            $scope.devices = $scope.stopServiceDevices;
        } else if (action === "inservice") {
            $scope.devices = $scope.inServiceDevices;
        } else if (action === "invalid") {
            $scope.devices = $scope.invalidServiceDevices;
        }
    };
    var map = new AMap.Map(map_container_id_name, {
        zoom: 10,
        center: [121.496548, 31.239432],
        animateEnable: false
    });
    map.plugin(["AMap.ToolBar"], function () {
        map.addControl(new AMap.ToolBar());
    });
    $scope.$on(CAR.event.list, function () {
        VehicleSrv.positions(function (carListResp) {
            map.clearMap();  // 清除地图覆盖物
            if (carListResp.code !== 0) {
                alert(carListResp.message);
                return;
            }
            $scope.init();
            $scope.carList = carListResp.data;
            if ($scope.carListMock && $scope.carListMock.length > 0) {
                $scope.carList = $scope.carList.concat($scope.carListMock);
            }
            for (var i = 0; i < $scope.carList.length; ++i) {
                var car = $scope.carList[i];
                var img = document.createElement('img');
                $(img).addClass("dashboard-car");
                if (car.status === 1) {
                    $(img).attr("src", "app/images/car/in-service.svg");
                    $(img).addClass("in-service");
                    $scope.inServiceDevices.push(car);
                } else if (car.status === 2) {
                    $(img).attr("src", "app/images/car/ready-service.svg");
                    $(img).addClass("ready-service");
                    $scope.readyServiceDevices.push(car);
                } else if (car.status === 3) {
                    $(img).attr("src", "app/images/car/stop-service.svg");
                    $(img).addClass("stop-service");
                    $scope.stopServiceDevices.push(car);
                } else {
                    $scope.invalidServiceDevices.push(car);
                    continue;
                }
                var marker = new AMap.Marker({
                    map: map,
                    position: [car.lng, car.lat],
                    offset: new AMap.Pixel(-20, -15),
                    content: img
                });
                marker.infoWindow = new AMap.InfoWindow({
                    isCustom: true, //使用自定义窗体
                    content: "<div class='ds-car-info-window'><div class='ds-car-info'>"
                    + "车牌:" + car.plate + "<br>"
                    + "状态:" + car.status_label + "<br>"
                    + "手机:" + car.mobile + "<br>"
                    + "司机:" + car.owner
                    + "</div></div>",
                    offset: new AMap.Pixel(6, -15)
                });
                AMap.event.addListener(marker, 'click', function (evt) {
                    if (evt.target.infoWindow.getIsOpen())
                        evt.target.infoWindow.close();
                    else
                        evt.target.infoWindow.open(map, evt.target.getPosition());
                });
            }
            $scope.readyServiceDeviceCount = $scope.readyServiceDevices.length;
            $scope.stopServiceDeviceCount = $scope.stopServiceDevices.length;
            map.setFitView();
        });
    });
    /*
     CarMockSrv.list(function (resp) {
     $scope.carListMock = resp.data;
     $scope.$broadcast(CAR.event.list);
     });//*/
    $scope.$broadcast(CAR.event.list);
})
.controller("DashboardAirMapViewCtrl", function ($rootScope, $scope, $routeParams, MAP, AIR, AirDeviceSrv, HIKESrv, AirDeviceMockSrv) {
    $rootScope.view = $routeParams.view;
    $scope.airDevices = null;
    $scope.alertPercolators = [];
    var w = $("#air-map-container-parent").width();
    var h = $(window).height();
    var min_height = MAP.map_min_height + MAP.map_info_panel;
    h = h < min_height ? min_height : h;
    var map_container_id_name = "air-map-container";
    var map_container_id = "#" + map_container_id_name;
    $(map_container_id).width(w);
    $(map_container_id).height(h - 400);
    $scope.airListTimer = setInterval(function () {
        // 60mins
        $scope.$broadcast(AIR.event.list);
    }, 60 * 1000 * 60);
    $scope.$on('$destroy', function () {
        // clear timer
        clearInterval($scope.airListTimer);
    });
    $scope.$on("WindowResize", function () {
        var w = $("#air-map-container-parent").width();
        var h = $(window).height();
        $(map_container_id).width(w);
        $(map_container_id).height(h - 310);
    });
    var map = new AMap.Map(map_container_id_name, {
        zoom: 10,
        center: [121.496548, 31.239432],
        animateEnable: false
    });
    map.plugin(["AMap.ToolBar"], function () {
        map.addControl(new AMap.ToolBar());
    });
    $scope.createMapElement = function (mac, pm25_measure, pm25_outdoor, tvoc, lang, lati, get_time, isOutdoor) {
        var div = document.createElement('div');
        $(div).css("border-radius", "5px")
        .css("background-color", $scope.getColorOfPM25(pm25_measure))
        .css("width", "65px")
        .css("height", "35px")
        .css("font-size", "24px")
        .css("color", "#fff")
        .css("text-align", "center");
        if (!isOutdoor) {
            $(div).css("border", "2px solid #565656");
        }
        div.innerHTML = isOutdoor ? pm25_outdoor : pm25_measure;
        var marker = new AMap.Marker({
            map: map,
            position: [lang, lati],
            offset: new AMap.Pixel(-30, -10),
            content: div
        });

        marker.infoWindow = new AMap.InfoWindow({
            isCustom: true, //使用自定义窗体
            content: "<div class='ds-car-info-window'><div class='ds-car-info'>"
            + "室外PM2.5: " + pm25_outdoor + "<br>"
            + "室内PM2.5: " + pm25_measure + "<br>"
            + "设备MAC: " + mac + "<br>"
            + "数据采集时间: " + get_time
            + "</div></div>",
            offset: new AMap.Pixel(6, -25)
        });
        AMap.event.addListener(marker, 'click', function (evt) {
            if (evt.target.infoWindow.getIsOpen())
                evt.target.infoWindow.close();
            else
                evt.target.infoWindow.open(map, evt.target.getPosition());
        });
    };
    $scope.$on(AIR.event.list, function () {
        map.clearMap();  // 清除地图覆盖

        if ($scope.airDevicesMock && $scope.airDevicesMock.length > 0) {
            for (var i = 0; i < $scope.airDevicesMock.length; ++i) {
                var device = $scope.airDevicesMock[i];
                if (device.expired)
                    continue;
                $scope.createMapElement(device.device_mac, device.pm25_measure, device.pm25_outdoor, 0, device.device_lang, device.device_lati, device.last_time, true);
            }
        }

        HIKESrv.all_data(function (res) {
            $scope.alertPercolators = [];
            if (res.code !== 0) {
                alert(res.message);
                return;
            }
            $scope.hikeDataList = res.data;
            for (var i = 0; i < $scope.hikeDataList.length; ++i) {
                var device = $scope.hikeDataList[i];
                if (device.filter1 === 0 || device.filter2 === 0 || device.filter3 === 0 || device.filter4 === 0) {
                    $scope.alertPercolators.push(device);
                }
                $scope.createMapElement(device.mac, device.pm25, 0, device.tvoc, device.lang, device.lati, device.gettime);
            }
        });

        AirDeviceSrv.last_data(function (deviceResponse) {
            if (deviceResponse.code !== 0) {
                alert(deviceResponse.message);
                return;
            }
            $scope.airDevices = deviceResponse.data;
            for (var i = 0; i < $scope.airDevices.length; ++i) {
                var device = $scope.airDevices[i];
                if (device.expired)
                    continue;
                $scope.createMapElement(device.device_mac, device.pm25_measure, device.pm25_outdoor, 0, device.device_lang, device.device_lati, device.last_time);
            }
        });
    });
    // Temp used
    AirDeviceMockSrv.list(function (resp) {
        $scope.airDevicesMock = resp.data;
        $scope.$broadcast(AIR.event.list);
    })//*/
    $scope.$broadcast(AIR.event.list);
});